package servlet;

import dao.CategoryDao;
import model.Category;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/categories")
public class CategoryServlet extends HttpServlet {
    private CategoryDao categoryDao = new CategoryDao();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            List<Category> categories = categoryDao.findAll();

            // 设置响应类型
            response.setContentType("application/json;charset=UTF-8");
            
            // 使用Jackson库将对象转换为JSON
            objectMapper.writeValue(response.getOutputStream(), categories);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(500);
        }
    }
}